package com.feihong.txgw.ui.activity.kaika;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.adapter.base.BaseQuickAdapter;
import com.blankj.utilcode.util.KeyboardUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.adapter.GirdDropDownAdapter;
import com.feihong.txgw.adapter.kaika.KaikaPhoneNumLiseReAdapter;
import com.feihong.txgw.inter.contract.kaika.IKaikaSelectPhoneNumContract;
import com.feihong.txgw.json.kaika.Menu;
import com.feihong.txgw.json.kaika.PhoneNumList;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.bean.kaika.KaikaYuYueOrderInfo;
import com.feihong.txgw.tx_precenter.KaikaSelectPhoneNumMainPrecenter;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.kaika.KaikaIntentType;
import com.yyydjk.library.DropDownMenu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * 待优化  无网络状态界面
 * Created by Sabirjan on 2017/7/3.
 * TXGWApp.
 * 飞宏电子
 * 开卡---第二步骤  选择号码
 * <p>
 * 第一步 根据ICCID获取筛选数据
 * 第二步 如果筛选数据空 则直接显示列表
 * 第三步 如果筛选数据不空 先绑定目筛选菜单数据
 * 第四步  获取列表数据
 */

public class KaiKaStep2Activity extends BaseMVPCompateActivity<IKaikaSelectPhoneNumContract.AbKakaSelectPhoneNumMainPrecenter> implements
        View.OnClickListener,
        IKaikaSelectPhoneNumContract.IKaikaSelectPhoneNumMainView,
        BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.dropDownMenu)
    DropDownMenu mDropDownMenu;
    @BindView(R.id.rel_contantframe)
    RelativeLayout rel_contantframe;
    @BindView(R.id.edit_phonenum)
    EditText edit_phonenum;
    @BindView(R.id.btn_back)
    ImageView mBackBtn;
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectErrorLayout;
    @BindView(R.id.re_query_data_layout)
    LinearLayout mRequeryDataLayout;
    @BindView(R.id.kaika_phoneNum_connecterror_Layout)
    RelativeLayout mConnectErrorContentLayout;
    @BindView(R.id.lay_loading)
    RelativeLayout mLoadLayout;

    private LinearLayoutManager mLinearLayoutManager;
    private KaikaPhoneNumLiseReAdapter mReAdapter;
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private View contentView;
    private String iccid = "";
    private Intent mTransIntent;
    private String mPackageId;

    private KaikaYuYueOrderInfo mKaikaYuYueOrderInfo;

    private ArrayList headers = new ArrayList();
    private List<View> popupViews = new ArrayList<>();
    private Menu menu;
    private boolean noMenuData = false;
    private HashMap<String, String> params = new HashMap<>();
    private String keyNumber = "";

    private String INTENT_FROM = "kaika";

    private boolean isFullPage = false, isHasData = false;

    @Override
    public void setTheme() {
        KaikaManager.getmKaikaManager().addStack(this);
        mTransIntent = getIntent();
        iccid = mTransIntent.getStringExtra(KaiKaActivity.INTENT_ICCID);
        mKaikaYuYueOrderInfo = KaikaYuYueOrderInfo.getInstance();
        mKaikaYuYueOrderInfo.setmPhoneNum(null);
        String keySign = mTransIntent.getStringExtra(KaikaIntentType.PHONE_NUMBER_INTENT_TYPE_KEY);
        if (!TextUtils.isEmpty(keySign)) {
            switch (keySign) {
                case KaikaIntentType.INTENT_FROM_PACKAGE_PAGE:
                    INTENT_FROM = KaikaIntentType.INTENT_FROM_PACKAGE_PAGE;
                    mPackageId = mKaikaYuYueOrderInfo.getmPackageId();
                    break;
                case KaikaIntentType.INTENT_FROM_YUYUE_PAGE:
                    INTENT_FROM = KaikaIntentType.INTENT_FROM_YUYUE_PAGE;
                    mPackageId = mTransIntent.getStringExtra(KaikaIntentType.SELECT_PACKAGE_ID_KEY);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_kaika_step2;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        mBackBtn.setOnClickListener(this);
        params = new HashMap<>();
        setPageTitle("选择号码");
        //init city menu
        contentView = getLayoutInflater().inflate(R.layout.kaika_step2_contentlayout, null);
        mRequeryDataLayout.setOnClickListener(this);
        findViewById(R.id.btn_searchnum).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyboardUtils.hideSoftInput(getActivity());
                if (edit_phonenum.getText() != null) {
                    keyNumber = edit_phonenum.getText().toString().trim();
                } else {
                    keyNumber = "";
                }
                mDropDownMenu.closeMenu();
            }
        });
    }

    /**
     * 根据ICCID获取筛选菜单数据
     */
    private void getMenuData() {
        mLoadLayout.setVisibility(View.VISIBLE);
        mPresenter.loadPhoneNumMenu(iccid);
    }


    private void addGridMenuItem(int pos) {
        //init constellation
        if (menu.getData().get(pos) == null) {
            return;
        }
        if (menu.getData().get(pos).getItems() == null || menu.getData().get(pos).getItems().size() == 0) {
            return;
        }
        String name = menu.getData().get(pos).getName();
        headers.add(name);
        ArrayList<String> menuitems = new ArrayList<>();
        for (Menu.MenuData.MenuItem item : menu.getData().get(pos).getItems()) {
            if (item.getId() != null && item.getName() != null && item.getName().trim().length() > 0) {
                menuitems.add(item.getName());
            }
        }
        final View constellationView = getLayoutInflater().inflate(R.layout.kaika_step2_menu_item, null);
        GridView constellation = (GridView) constellationView.findViewById(R.id.constellation);
        GirdDropDownAdapter constellationAdapter = new GirdDropDownAdapter(this, menuitems);
        constellation.setAdapter(constellationAdapter);
        constellation.setTag(pos);
        //init popupViews
        popupViews.add(constellationView);
        constellation.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    int pos = 0;
                    GirdDropDownAdapter mGirdDropDownAdapter = (GirdDropDownAdapter) parent.getAdapter();
                    if (mGirdDropDownAdapter.getCheckItemPosition() == position) {
                        mDropDownMenu.closeMenu();
                        return;
                    }
                    pos = Integer.parseInt(parent.getTag().toString());
                    params.remove(menu.getData().get(pos).getReqname());

                    mGirdDropDownAdapter.setCheckItem(position);
                    String paramVal = menu.getData().get(pos).getItems().get(position).getId();
                    String paramName = menu.getData().get(pos).getItems().get(position).getName();
                    if (position == 0) {
                        paramName = menu.getData().get(pos).getName();
                    } else {
                        params.put(menu.getData().get(pos).getReqname(), paramVal);
                    }
                    mDropDownMenu.setTabText(paramName);
                    mSwipeRefreshLayout.setRefreshing(true);
                    getPhoneNumDataFirst();
                } catch (Exception ex) {

                }
                mDropDownMenu.closeMenu();
            }
        });
    }


    @Override
    public void bindData() {
        super.bindData();
        getMenuData();
        mLinearLayoutManager = new LinearLayoutManager(this);
    }

    private void initAdapter() {
        mReAdapter = new KaikaPhoneNumLiseReAdapter(R.layout.kaika_phonenumlist_item);
        mReAdapter.setOnLoadMoreListener(this, mRecyclerView);
        mReAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                PhoneNumList.PhoneNumItem adapterItemData = (PhoneNumList.PhoneNumItem) adapter.getItem(position);
                Intent intent = new Intent();
                if ("kaika".equals(INTENT_FROM)) {
                    Log.i(TAG, "onItemClick: " + iccid + "   " + adapterItemData.getPhonenum() + adapterItemData.getId());
                    intent.setClass(KaiKaStep2Activity.this, KaiKaStep3Activity.class);
                    intent.putExtra(KaiKaActivity.INTENT_ICCID, iccid);
                    intent.putExtra(KaiKaActivity.INTENT_PHOE_NUM, adapterItemData.getPhonenum());
                    intent.putExtra(KaiKaActivity.INTENT_PHOE_NUM_ID, adapterItemData.getId());
                    startActivity(intent);
                } else if (KaikaIntentType.INTENT_FROM_PACKAGE_PAGE.equals(INTENT_FROM)) {
                    mKaikaYuYueOrderInfo.setmPhoneNum(adapterItemData.getPhonenum());
                    intent.setClass(KaiKaStep2Activity.this, KaikaNoCardOperateActivity.class);
                    startActivity(intent);
                } else if (KaikaIntentType.INTENT_FROM_YUYUE_PAGE.equals(INTENT_FROM)) {
                    mKaikaYuYueOrderInfo.setmPhoneNum(adapterItemData.getPhonenum());
                    intent.setClass(KaiKaStep2Activity.this, KaikaNoCardOperateActivity.class);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mRecyclerView.setAdapter(mReAdapter);
    }

    /**
     * 显示条件菜单
     */
    private void setMenuData() {
        if (noMenuData) {
            rel_contantframe.removeAllViews();
            rel_contantframe.addView(contentView);
        } else {
            headers = new ArrayList();
            popupViews = new ArrayList<>();
            //绑定目录
            for (int i = 0; i < menu.getData().size(); i++) {
                addGridMenuItem(i);
            }
            //init dropdownview
            mDropDownMenu.setVisibility(View.VISIBLE);
            mDropDownMenu.setDropDownMenu(headers, popupViews, contentView);
        }
        initListView();
    }

    /**
     * 初始化号码列表
     */
    private void initListView() {
        mSwipeRefreshLayout = contentView.findViewById(R.id.refresh);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(223, 47, 47));
        mRecyclerView = contentView.findViewById(R.id.kaika_phoneNum_recyclerView);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getPhoneNumDataFirst();
            }
        });
        mSwipeRefreshLayout.setRefreshing(true);
        initAdapter();
        getPhoneNumDataFirst();
    }

    /**
     * 获取手机号码列表入口
     */
    private void getPhoneNumListData() {
        mPresenter.loadPhoneNumList(iccid, keyNumber, mPackageId, params);
    }

    /**
     * 首次获取号码
     */
    private void getPhoneNumDataFirst(){
        isFullPage = false;
        isHasData = false;
        mPresenter.loadPhoneNumListFirst(iccid,keyNumber,mPackageId,params);
    }
    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.re_query_data_layout:
                mConnectErrorLayout.setVisibility(View.GONE);
                getMenuData();
                break;
            default:
                break;
        }
    }

    @Override
    public void loadPhoneNumMenuResult(Menu result) {
        mConnectErrorContentLayout.setVisibility(View.GONE);
        rel_contantframe.setVisibility(View.VISIBLE);
        mLoadLayout.setVisibility(View.GONE);
        menu = result;
        if (menu != null && menu.getCode() == 200) {
            if (menu.getData() == null || menu.getData().size() == 0) {
                //没有筛选数据
                noMenuData = true;
            }
            setMenuData();
        } else {
            noMenuData = true;
            setMenuData();
        }
    }

    @Override
    public void loadPhoneNumMenuError() {
        mConnectErrorContentLayout.setVisibility(View.VISIBLE);
        mConnectErrorLayout.setVisibility(View.VISIBLE);
        rel_contantframe.setVisibility(View.GONE);
        mLoadLayout.setVisibility(View.GONE);
    }

    @Override
    public void loadPhoneNumListResult(boolean isFullPage, List<PhoneNumList.PhoneNumItem> phoneNumItems) {
        this.isFullPage = isFullPage;
        if (isHasData) {
            mReAdapter.addData(phoneNumItems);
        } else {
            mReAdapter.setNewData(phoneNumItems);
            isHasData = true;
        }
        if(isFullPage){
            mReAdapter.loadMoreComplete();
        }else {
            mReAdapter.loadMoreEnd(!isFullPage);
        }
    }

    @Override
    public void loadPhoneNumListError() {
        mReAdapter.loadMoreFail();
        finishRefreshing();
        showDialog(null, getString(R.string.connect_service_error));
    }

    @Override
    public void loadPhoneNumEnd() {
        mReAdapter.loadMoreEnd(!isFullPage);
    }

    @Override
    public void loadPhoneNumOhterError() {

    }

    @Override
    public void loadDataComplated() {
        finishRefreshing();
    }

    @Override
    public void loadDataError() {
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return KaikaSelectPhoneNumMainPrecenter.create();
    }

    @Override
    public void onLoadMoreRequested() {
        getPhoneNumListData();
    }

    /**
     * 结束刷新状态
     */
    private void finishRefreshing() {
        if (mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //退出activity前关闭菜单
            if (mDropDownMenu.isShowing()) {
                mDropDownMenu.closeMenu();
                return true;
            } else {
                finish();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
